<template>
    <div class="brs-uploader">
        <div class="brs-uploader-wrapper">
            <div class="brs-uploader-wrapper__item" v-for="(item, index) in changeList" :key="index">
                <div class="brs-uploader-wrapper__item-image" @click="$emit('clickItem', {data: item, index: index})">
                    <img :src="item.base64" alt="" v-if="item.status === 2 || item.status === 3">
                    <img :src="item.url" alt="" v-if="item.status === 5">
                </div>
                <div class="brs-uploader-wrapper__item-loading" v-if="item.status === 1 || item.status === 3">
                    <span v-if="item.status === 1">压缩中...</span>
                    <span v-if="item.status === 3">上传中...</span>
                </div>
                <div class="brs-uploader-wrapper__item-delete" v-if="item.status !== 1 && item.status !== 3" @click="changeList.splice(index, 1)">X</div>
            </div>
            <div class="brs-uploader-wrapper__item brs-uploader-wrapper__add" v-if="!length || (changeList.length < length)">
                <span>+</span>
                <input type="file" ref="fileElement" @change="changeHandle" :accept="accept">
            </div>
        </div>
    </div>
</template>

<script>
/**
{
    id: new Date().getTime(), // 当前时间戳作为id
    file: file, // 原始对象
    status: 1, // 状态 1：压缩中，2：压缩成功，3：上传中，4：上传失败，5：上传成功
    url: '', // 上传成功后返回的url
    base64: '', // 原始对象压缩后的base64编码
}
 */
export default {
    name: 'brs-uploader',
    props: {
        autoUpload: {
            type: Boolean,
            default: false
        }, // 压缩完成之后是否自动上传
        length: {
            type: Number,
            default: 0
        }, // 可选个数
        accept: {
            type: String,
            default: '*'
        }, // 可选的文件类型
        list: {
            type: Array,
            default(){
                return []
            }
        }, // 默认值（要自己模拟id，status等字段）
    },
    data(){
        return {
            changeList: []
        }
    },
    watch: {
        list(){
            this.changeList = this.list
        },
        changeList: {
            handler(val){
                this.$emit('change', val)
            },
            deep: true
        }
    },
    methods: {
        async changeHandle(e){
            const file = e.target.files[0]
            let id = new Date().getTime()
            let obj = {
                id: id,
                file: file,
                status: 1,
                url: '',
                base64: ''
            }
            this.changeList.push(obj)
            // 立即清空，防止选同一张无效
            this.$refs.fileElement.value = null;
            let res = await window.common.compressImageByFile(file)
            if(res.code === 0){
                let base64 = await window.common.compressImg(file)
                if(base64){
                    let i = -1;
                    for (let index = 0; index < this.changeList.length; index++) {
                        const element = this.changeList[index];
                        if(element.id === id){
                            i = index;
                            break;
                        }
                    }
                    if(i >= 0){
                        this.$set(this.changeList, this.changeList[i], Object.assign(this.changeList[i], { base64: base64, status: 2}))
                        if(this.autoUpload){
                            this.$set(this.changeList, this.changeList[i], Object.assign(this.changeList[i], { status: 3}))
                            this.upload(this.changeList[i])
                        }
                    }
                }
            }
        },
        // 上传（这里只是做模拟上传，真正上传需要后端接口）
        upload(item){
            setTimeout(() => {
                let i = -1;
                for (let index = 0; index < this.changeList.length; index++) {
                    const element = this.changeList[index];
                    if(element.id === item.id){
                        i = index;
                        break;
                    }
                }
                if(i >= 0){
                    this.$set(this.changeList, this.changeList[i], Object.assign(this.changeList[i], { url: item.base64, status: 5}))
                }
            }, 2100)
        }
    }
}
</script>

<style lang="less" scoped>
    .brs-uploader{
        .brs-uploader-wrapper{
            display: flex;
            flex-flow: wrap;
            width: 100%;
            overflow: hidden;
            margin-left: -20px;
            margin-top: -20px;
            .brs-uploader-wrapper__item{
                width: 200px;
                height: 200px;
                overflow: hidden;
                position: relative;
                margin-left: 20px;
                margin-top: 20px;
                background-color: #ddd;
                .brs-uploader-wrapper__item-image{
                    position: relative;
                    z-index: 1;
                    width: 100%;
                    height: 100%;
                    img{
                        width: 100%;
                        height: 100%;
                        object-fit: cover;
                        float: left;
                    }
                }
                .brs-uploader-wrapper__item-delete{
                    position: absolute;
                    top: 0;
                    right: 0;
                    z-index: 2;
                    width: 50px;
                    height: 50px;
                    background-color: @default-main-color;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    color: #fff;
                    font-size: 20px;
                }
                .brs-uploader-wrapper__item-loading{
                    position: absolute;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    left: 0;
                    z-index: 3;
                    background: rgba(0, 0, 0, .5);
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    span{
                        color: #fff;
                        font-size: 20px;
                    }
                }
            }
            .brs-uploader-wrapper__add{
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 100px;
                input{
                    position: absolute;
                    top: 0;
                    right: 0;
                    bottom: 0;
                    left: 0;
                    opacity: 0;
                }
            }
        }
    }
</style>